  package client;
  
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.DefaultButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
 /**
  * This is an implementation of a simple spin box suitable for use
  * with positive integers. It displays as a text area with two small
  * up and down buttons beside it. Pressing the up or down button increments
  * or decrements the counter. Pressing and holding either button causes the
  * value to change continuously (unless delay is set to 0).
  */
 public class SpinBox extends JFrame
 {
	 public int count = 0;
	 static final long serialVersionUID = 200503311127L;
	 public boolean sbFlag = false;  
	 JLabel l = null;
	 boolean removeFlag = false;
	 public int initValue = 0; 
	 
   		/**
   		 * Creates a spin box
   		 * @param init The initial value for the spin box
   		 * @param min The minimum value for the spin box
   		 * @param max The maximum value for the spin box
   		 */
      public SpinBox(int init, int min, int max)
  	  {
          if (min<0 || max<min || init<min || init>max)
              throw new IllegalArgumentException("Invalid initial parameters for spin box");
          
          this.value = init;
          this.min = min;
          this.max = max;
          
          this.initValue = init;
          JPanel p = new JPanel();
          p.setLayout(null);
          
          valueChanging = true;
          field = new JTextField(new SpinDocument(),String.valueOf(init),(int) (1+Math.log(Math.abs(max))/Math.log(10)));
          field.setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,25));
          this.setBackground(Color.LIGHT_GRAY);
          this.setPreferredSize(new Dimension(205,175));
          this.setResizable(false);
          valueChanging = false;
          valueChanged();
          
          plus.setMargin(new Insets(0,0,0,0));
          plus.setModel(new MachineGunButtonModel());
          plus.setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,25));
          minus.setMargin(new Insets(0,0,0,0));
          minus.setModel(new MachineGunButtonModel());
          minus.setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,25));
          
          this.addWindowListener(new WindowAdapter() 
          {
        	  public void windowClosing(WindowEvent e) 
        	  {
        		  if(Main.catalog.callFrom.equals("Costum")) 
             	  {
        			  Main.customOrder.setEnabled(true);
        			  Main.customOrder.setVisible(true);
             	  }
        		  else
        			  if(Main.catalog.callFrom.equals("Cart")) 
                 	  {
        				  Main.catalog.setEnabled(true);
        				  Main.catalog.setVisible(true);
                 	  }
        		  dispose();
        	  }
          });
         
          if(Main.catalog.callFrom.equals("Costum"))
          {
        	  if(Main.customOrder.callFrom.equals("CustomBox"))
     		  {		  
	        	  l = new JLabel(+Main.customId+" - Custom "+Main.customOrder.Type+"");
	        	  l.setBounds(1, 2, 150, 18);
	        	  p.add(l);
     		  }
        	  else
        		  if(Main.customOrder.callFrom.equals("existingCostum"))
         		  {
        			  l = new JLabel((String) Main.customOrder.existingCostum.getSelectedItem());
    	        	  l.setBounds(1, 2, 150, 18);
    	        	  p.add(l);
         		  }
          }
          else
        	  if(Main.catalog.callFrom.equals("Cart"))
        	  {
        		  l = new JLabel("Item name : "+(String)Main.catalog.table.getValueAt(Main.catalog.table.getSelectedRow(), 0));
        		  l.setBounds(1, 2, 150, 18);
        		  p.add(l);
        	  }
          
          plus.setBounds(145, 30, 50, 30);
          minus.setBounds(5, 30, 50, 30);
          field.setBounds(60, 30, 75, 30);
          Set.setBounds(5, 75, 190, 30);
          Remove.setBounds(5, 110, 190, 30);
          p.add(plus);
          p.add(minus);
          p.add(field);
          p.add(Set);
          p.add(Remove);
          
          this.add(p);
          this.pack();
          this.setVisible(true);
          
          Set.addActionListener(new ActionListener()
  	      {
              @SuppressWarnings("static-access")
			public void actionPerformed(ActionEvent e)
  	        {
            	 String itemName = (String)Main.catalog.table.getValueAt(Main.catalog.table.getSelectedRow(), 0); 
            	 
            	 if(Main.catalog.callFrom.equals("Costum")) 
            	 {	
            		 Object ttemp = null;
            		 int cid = -1;
            		 Object type = null;
            		 
            		 if(getValue() == 0 && initValue != 0) 
            		 {
            			 int msg = JOptionPane.showConfirmDialog(null, "Are you sure you want to remove this item? ","Confirmation" ,JOptionPane.OK_CANCEL_OPTION);
	            		 if(msg == 2)		//CANCEL = 2 //OK = 0	
	            			removeFlag = true;
            		 }		
            		 
            		 if(Main.customOrder.callFrom.equals("CustomBox"))
            		 { 
            			 	cid = Main.customId;
            			 	ttemp = +Main.customId+" - Custom "+Main.customOrder.Type+"";
            		 		type = Main.customOrder.Type;
            		 }	
            		 else 
            			 if(Main.customOrder.callFrom.equals("existingCostum"))
	            		 {
	            			ttemp = Main.customOrder.existingCostum.getSelectedItem();
	            			type = ((String) ttemp).substring(11, ((String) ttemp).length());    
	            			cid = Integer.parseInt(((String) ttemp).substring(0, 1));        			 
	            		 }
            		 
            		 	if(removeFlag == false)
            		 	{
            		 		Object[] tempCostum = new Object[7];	
            		 		tempCostum[0] = LogIn.usr.getID();			//user id
            		 		tempCostum[1] = cid;						//custom item id
            		 		tempCostum[2] = Main.catalog.table.getValueAt(Main.catalog.table.getSelectedRow(), 5); 	   //item id
            		 		tempCostum[3] = (Float)Main.catalog.table.getValueAt(Main.catalog.table.getSelectedRow(), 3); //item price
            		 		tempCostum[4] = ttemp;	 		 			//item name
            		 		tempCostum[5] = type;						//item type
            		 		tempCostum[6] = getValue();                 //item quantity in custom 	
	            		 
            		 			if(initValue != (Integer)tempCostum[6])	
            		 			{	 
            		 				if(Main.cart_Control != null)
        		   		 				Main.cart_Control = null;
            		 				Main.cart_Control = new Cart("setCostumData", tempCostum);
            		 				int result = (Integer)Main.clie.getResult();
				            		System.out.println(result);
				            		 
						            if(result == 1)
						            	JOptionPane.showMessageDialog(null, ""+(Integer)tempCostum[6]+" "+itemName+" have been added to your ("+cid+") custom item in cart");
						            else 
						            	if(result == 2 && initValue != (Integer)tempCostum[6])
						            		JOptionPane.showMessageDialog(null, "Your cart has been updated : "+(Integer)tempCostum[6]+" "+itemName+" are now in your custom item ("+cid+") in cart");
						            else 
						            	if(result == 3 && initValue != 0)
						            		JOptionPane.showMessageDialog(null, ""+(initValue-(Integer)tempCostum[6])+" "+itemName+" have been removed from custom item ("+cid+") in your cart");
            		 			}
				            	else 
			            		{
			            			setValue(initValue);
			            			removeFlag = false;
			            			dispose();
			            		}
            		 	} 
            		 	else 
	            		{
	            			setValue(initValue);
	            			removeFlag = false;
	            		}
            		 	Main.catalog.setEnabled(true);
		             	Main.catalog.setVisible(true);
		             	dispose();
		             	Main.customOrder.dispose();
		            		 
            	 }
         	 
            	 else
            		 if(Main.catalog.callFrom.equals("Cart")) 
	            	 {
	            		 if(getValue() == 0 && initValue != 0) 
	            		 {
	            			 int msg = JOptionPane.showConfirmDialog(null, "Are you sure you want to remove this item? ","Confirmation" ,JOptionPane.OK_CANCEL_OPTION);
		            		 if(msg == 2)		//CANCEL = 2 //OK = 0	
		            			removeFlag = true;
	            		 }									
	            		 
	            		 if(removeFlag == false)
	            		 {
			            	Object[] temp = new Object[4];
			            	temp[0] = LogIn.usr.getID();
			            	temp[1] = Main.catalog.table.getValueAt(Main.catalog.table.getSelectedRow(), 5); //item id    
			            	temp[2] = getValue();	 														 //item quantity
			            	temp[3] = (float)getValue()*(Float)Main.catalog.table.getValueAt(Main.catalog.table.getSelectedRow(), 3); 
			            	
				            	if(initValue != (Integer)temp[2])	
				            	{
				            		if(Main.cart_Control != null)
        		   		 				Main.cart_Control = null;
            		 				Main.cart_Control = new Cart("setData", temp);
					            	int result = (Integer)Main.clie.getResult();
					            	System.out.println(result);
					          
					            	if(result == 1)
					            		JOptionPane.showMessageDialog(null, ""+(Integer)temp[2]+" "+itemName+" have been added to your cart");
					            	else 
					            		if(result == 2 && initValue != (Integer)temp[2])
					            			JOptionPane.showMessageDialog(null, "Your cart has been updated : "+(Integer)temp[2]+" "+itemName+" are now in your cart");
					            	else 
					            		if(result == 3 && initValue != 0)
					            			JOptionPane.showMessageDialog(null, ""+(initValue-(Integer)temp[2])+" "+itemName+" have been removed from your cart");
				            	}
				            	else 
			            		{
			            			setValue(initValue);
			            			removeFlag = false;
			            		}
			             }
	            		 else 
	            		 {
	            			 setValue(initValue);
	            			 removeFlag = false;
	            		 }
			             Main.catalog.setEnabled(true);
			             Main.catalog.setVisible(true);
			             dispose();
	            	 }
         	  }
          });
          
          Remove.addActionListener(new ActionListener()
          {
        	  public void actionPerformed(ActionEvent e)
    	      {
        		  setValue(0);
        		  Set.doClick();
    	      }
          });
          
          plus.addActionListener(new ActionListener()
  	      {
              public void actionPerformed(ActionEvent e)
  	          {
                  value++;
                  valueChanged();
              }
          });
          minus.addActionListener(new ActionListener()
  	      {
              public void actionPerformed(ActionEvent e)
             {
                  value--;
                  valueChanged();
              }
          });
      }
      public void addActionListener(ActionListener l)
  	  {listener.addElement(l);}
      public void removeActionListener(ActionListener l)
  	  {listener.removeElement(l);}
      
      private void fireActionListener()
  	  {
          ActionEvent event = new ActionEvent(this,ActionEvent.ACTION_FIRST,"hi");
          Enumeration e = listener.elements();
          while (e.hasMoreElements())
  	      {
              ((ActionListener) e.nextElement()).actionPerformed(event);
          }
      }
      private void valueChanged()
  	  {
          if (value > max) value = max;
          if (value < min) value = min;
          
         plus.setEnabled(value < max);
         minus.setEnabled(value > min);
         if (!valueChanging)
 	     {
             valueChanging = true;
             field.setText(String.valueOf(value));
             valueChanging = false;
         }
         fireActionListener();
     }
     
     public void setMin(int value)
 	 {min = value;}
     public void setMax(int value)
     {max = value;}
     
     public int getMin()
 	 {return min;}
     public int getMax()
 	 {return max;}
     
     public int getValue()
 	 {return value;}
     public void setValue(int value)
 	 {
    	 this.value = value;
         valueChanged();
     }
     public int getRepeatDelay()
 	 {return delay;}
     /**
      * Sets the delay for the repeat function of the arrow keys.
      * @param The delay between increments in milliseconds, or 0 to disable repeat
      */
     public void setRepeatDelay(int delay)
 	 {
         if (delay < 0) throw new IllegalArgumentException("Invalid repeatDelay set");
         this.delay = delay;
     }
     public void setEnabled(boolean enabled)
 	 {
         plus.setEnabled(enabled);
         minus.setEnabled(enabled);
         field.setEnabled(enabled);
         Set.setEnabled(enabled);
         super.setEnabled(enabled);
     }
     private int max = Integer.MAX_VALUE;
     private int min = 0;
     private int value = 0;
     
     private int delay = 50;
     private boolean valueChanging = false;
     public JTextField field;
     public JButton plus = new JButton("+");
     public JButton minus = new JButton("-");
     public  JButton Set = new JButton("Set");
     public  JButton Remove = new JButton("Remove");
     private Vector<ActionListener> listener = new Vector<ActionListener>();
     
     private class MachineGunButtonModel extends DefaultButtonModel implements ActionListener
 	 {
         static final long serialVersionUID = 200503311126L;
                 
         public void setPressed(boolean b)
 	     {
             if (!b && timer != null && timer.isRunning()) 
            	 timer.stop();
             
             if((isPressed() == b) || !this.isEnabled())
 	         {
                 return;
             }
             if (b)
 	         {
                 stateMask |= PRESSED;
             } 
             else
 	         {
                 stateMask &= ~PRESSED;
             }
             
             if (isPressed() && isArmed())
 	         {
                 fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED,getActionCommand()));
             }
             if (timer == null && isPressed() && delay > 0)
 	         {
                 timer = new Timer(delay,this);
                 timer.setInitialDelay(500);
             }
             if (isPressed()) 
            	 timer.start();
             
             fireStateChanged();
         }
         public void actionPerformed(ActionEvent e)
 	     {
             if (this.isEnabled() && isArmed() && isPressed())
 	         {
                 fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, getActionCommand()));
             }
         }
         private Timer timer;
     }
     
     private class SpinDocument extends PlainDocument implements Runnable
 	 {
         static final long serialVersionUID = 200503311125L;
                 
         public void insertString(int pos, String string, AttributeSet p3) throws BadLocationException
 	     {
             if (!valueChanging)
 	         {
                 for (int i=0; i<string.length(); i++)
 	             {
                     if (!Character.isDigit(string.charAt(i)))
 	                 {
                         getToolkit().beep();
                         return;
                     }
                 }
             }
             
             super.insertString(pos, string, p3);
             if (!valueChanging)
 	         {
                 int nValue = Integer.parseInt(field.getText());
                 if (nValue < min || nValue > max)
 	             {
                     super.remove(pos,string.length());
                     getToolkit().beep();
                     return;
                 }
                 value = nValue;
                 valueChanging = true;
                 valueChanged();
                 valueChanging = false;
             }
         }
         public void remove(int pos, int len) throws BadLocationException
 	          {
             // Things are complicated here by the fact that the remove may be just
             // the first part of a replace, so we cant simply test for a illegal value
             // after the remove, in case an insert is to follow immediately. Instead we
             // queue a later check on the validity of the field.
             super.remove(pos,len);
             SwingUtilities.invokeLater(this);
         }
         public void run()
 	     {
             if (field == null) return;
             String text = field.getText();
             int nValue;
             if (text.length() == 0)
 	         {
                 nValue = Integer.MIN_VALUE;
             }
             else
 	         {
                 nValue = Integer.parseInt(field.getText());
             }
             if (nValue < min)
 	         {
                 nValue = min;
                 getToolkit().beep();
                 field.setText(String.valueOf(nValue));
             }
             value = nValue;
             valueChanging = true;
             valueChanged();
             valueChanging = false;
         }
     }
 }